package com.itheima.service.impl;


import com.itheima.dao.QuestionItemDao;
import com.itheima.domain.QuestionItem;
import com.itheima.service.QuestionItemService;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;


import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;

public class QuestionItemServiceImpl implements QuestionItemService {

    @Override
    public void save(QuestionItem questionItem) {
        SqlSession sqlSession=null;
        try {
             sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao mapper = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);
            //生成一个唯一的id，保存到questionItem
            String id = UUID.randomUUID().toString().replace("-", "");
            questionItem.setId(id);
            mapper.save(questionItem);
            MybatisUtil.commit(sqlSession);

        } finally {
            MybatisUtil.close(sqlSession);
        }
    }

    @Override
    public QuestionItem findById(String id) {
        QuestionItem questionItem = null;
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao mapper = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);

            questionItem =  mapper.findById(id);
            MybatisUtil.commit(sqlSession);

        } finally {
            MybatisUtil.close(sqlSession);
        }
        return questionItem;
    }

    @Override
    public void update(QuestionItem questionItem) {
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao mapper = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);

            mapper.update(questionItem);
            MybatisUtil.commit(sqlSession);

        } finally {
            MybatisUtil.close(sqlSession);
        }
    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao mapper = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);

            mapper.delete(id);
            MybatisUtil.commit(sqlSession);

        } finally {
            MybatisUtil.close(sqlSession);
        }
    }

    @Override
    public List<QuestionItem> findAll(String questionId) {
        List<QuestionItem> list = null;
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            QuestionItemDao mapper = MybatisUtil.getMapper(sqlSession, QuestionItemDao.class);

            list = mapper.findAll(questionId);
            MybatisUtil.commit(sqlSession);

        } finally {
            MybatisUtil.close(sqlSession);
        }
        return list;
    }
}
